import os
import time
import mypyutils.system
import mypyutils.files
from setup_requirements import setup_requirements
#from patch_requirements import patch_requirements

DEFAULT_VIRTUALENV_DIR = os.path.join('..', '..', 'virtualenv')
DEFAULT_REQUIREMENTS_DIR = os.path.join('..', 'requirements')
DEFAULT_PACKAGE_EXTENSIONS = '*.zip;*.tar.gz;*.tgz'
DEFAULT_TEMP_DIR = 'temp'
VIRTUALENV_SETUP_DIR = 'virtualenv-1.5.1'

def install(virtualenvDir=DEFAULT_VIRTUALENV_DIR,
          requirementsDir=DEFAULT_REQUIREMENTS_DIR,
          packageExtensions=DEFAULT_PACKAGE_EXTENSIONS,
          tempDir=DEFAULT_TEMP_DIR):
    
    def adjust_options(options, args):
        '''
        Set the command line argument for the directory of the new virtual environment
        '''
        args.append(virtualenvDir)
        #options.relocatable = True
        
    def after_install(options, home_dir):
        setup_requirements(requirementsDir, virtualenvDir, tempDir, packageExtensions)
    
    startDir = os.getcwd()
    try:    
        os.chdir(os.path.dirname(__file__))
        
        virtualenvDir = os.path.abspath(virtualenvDir)
        if not os.path.isdir(os.path.dirname(virtualenvDir)):
            raise Exception('virtualenvDir is invalid: ' + virtualenvDir)
        
        requirementsDir = os.path.abspath(requirementsDir)
        if not os.path.isdir(requirementsDir):
            raise Exception('requirementsDir is invalid: ' + requirementsDir)
        
        tempDir = os.path.abspath(tempDir)
        if not os.path.isdir(os.path.dirname(tempDir)):
            raise Exception('tempDir is invalid: ' + tempDir)
        
        mypyutils.files.forced_rmtree(virtualenvDir)
        time.sleep(0.2)
    
        virtualenvPy = os.path.abspath(os.path.join(VIRTUALENV_SETUP_DIR, 'virtualenv.py'))
        virtualenvGlobals = dict(globals())
        virtualenvGlobals['__file__'] = virtualenvPy
        virtualenvGlobals['__name__'] = '__main__'
        virtualenvGlobals['adjust_options'] = adjust_options
        virtualenvGlobals['after_install'] = after_install
        execfile(virtualenvPy, virtualenvGlobals)
    finally:
        os.chdir(startDir)
    

if __name__ == '__main__':
    virtualenvDir = mypyutils.system.arg(1, DEFAULT_VIRTUALENV_DIR)
    requirementsDir = mypyutils.system.arg(2, DEFAULT_REQUIREMENTS_DIR)
    packageExtensions = mypyutils.system.arg(4, DEFAULT_PACKAGE_EXTENSIONS)
    tempDir = mypyutils.system.arg(3, DEFAULT_TEMP_DIR)
    install(virtualenvDir, requirementsDir, packageExtensions, tempDir)
